package store

import (
	"database/sql"
	"errors"
	"log"
	"path"
	"time"

	"github.com/Unknwon/com"
	"smartconn.cc/tosone/ra_main/common"
	"smartconn.cc/tosone/ra_main/config"
)

const pageSchema = "(\"pageID\" TEXT, \"serverPageID\" TEXT, \"feature\" TEXT, \"role\" TEXT, \"manifest\" TEXT, \"count\" INTEGER, \"date\" TEXT)"
const pageSchemaPure = "(\"pageID\", \"serverPageID\", \"feature\", \"role\", \"manifest\", \"count\", \"date\")"

// Database Database
type Database struct {
	DB *sql.DB
}

// OpenStory open
func OpenStory(dir string) (db Database, err error) {
	if !com.IsDir(dir) {
		err = errors.New("No such a directory")
		return
	}
	db.DB, err = sql.Open("sqlite3", path.Join(dir, config.SlaveDB))
	log.Println(path.Join(dir, config.SlaveDB))
	if err != nil {
		log.Println(err)
	}
	return db, err
}

// Close close
func (db Database) Close() {
	db.DB.Close()
}

// SetPage setpage
func (db Database) SetPage(info map[string]interface{}) {
	_, err = db.DB.Exec("INSERT INTO \"page\" "+pageSchema+" VALUES "+paramsNums(pageSchema), info["pageID"], info["serverPageID"], info["feature"], info["role"], info["manifest"], 0, time.Now().Format(time.RFC3339))
	if err != nil {
		log.Println(err)
		return
	}
}

// UpdatePage updatepage
func (db Database) UpdatePage(info map[string]interface{}) {
	_, err = db.DB.Exec("UPDATE \"page\" SET \"manifest\"=?, \"count\"=?, \"feature\"=? WHERE \"pageID\"=?", info["manifest"], info["count"], info["feature"], info["pageID"])
	if err != nil {
		log.Println(err)
		return
	}
}

// UpdatePageCount updatePageCount
func (db Database) UpdatePageCount(pageID string, count int) {
	_, err = db.DB.Exec("UPDATE \"page\" SET \"count\"=? WHERE \"pageID\"=?", count, pageID)
	if err != nil {
		log.Println(err)
		return
	}
}

// GetPage 获取某一页的信息
func (db Database) GetPage(p, m string) (info map[string]interface{}) {
	var pageID, serverPageID, role, manifest, date string
	var count int
	err = db.DB.QueryRow("SELECT \"pageID\", \"serverPageID\", \"role\", \"manifest\", \"count\", \"date\" FROM \"page\" WHERE \"pageID\"="+p+" and \"role\"="+m).Scan(&pageID, &serverPageID, &role, &manifest, &count, &date)
	switch {
	case err == sql.ErrNoRows:
		return
	case err != nil:
		log.Println(err)
	default:
		info = map[string]interface{}{"pageID": pageID, "serverPageID": serverPageID, "role": role, "manifest": manifest, "count": count, "date": date}
	}
	return
}

// GetPages 获取所有的 page
func (db Database) GetPages() (pages []common.FeatureWithID) {
	rows, err := db.DB.Query("SELECT \"feature\",\"BookID\" FROM \"page\"")
	if err != nil {
		log.Println(err)
		return
	}
	var feature, id string
	for rows.Next() {
		err := rows.Scan(&feature, &id)
		if err != nil {
			log.Println(err)
			return
		}
		pages = append(pages, common.FeatureWithID{Feature: feature, ID: id})
	}
	return
}
